import {Component, OnInit, ViewChild} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
import {ENgxEditorComponent} from 'e-ngx-editor';
import {HttpClient} from '@angular/common/http';
import * as _ from 'lodash';

@Component({
  selector: 'app-publish',
  templateUrl: './publish.component.html',
  styleUrls: ['./publish.component.scss']
})
export class PublishComponent implements OnInit {
  //  保存状态与时间
  saveStatus;
  date: any;
  // 封面图片
  coverImage: any;
  coverImageUrl: any;
  //  发布文章的标题
  publishTitle: any;
  // 编辑器
  @ViewChild('editor') editor: ENgxEditorComponent;
  editorData: any;
  // 发布状态
  publishFlag = '发布';

  // token
  token;

  constructor(private sanitizer: DomSanitizer,
              private http: HttpClient) {
  }

  ngOnInit() {
    // this.http.post('http://47.93.57.133/api/v1/api-token-auth/',
    //   {
    //     'username': 'admin',
    //     'password': 'admin123',
    //   })
    //   .subscribe(
    //     (val) => {
    //       alert('登录成功');
    //       this.token = val['token'];
    //     },
    //     response => {
    //       alert('登录失败');
    //     },
    //     () => {
    //       console.log('The POST observable is now completed.');
    //     });
    window.onresize = function () {
      document.getElementById('edui1').style.width = '100%';
      document.getElementById('edui1_toolbarbox').style.width = '100%';
      document.getElementById('edui1_iframeholder').style.width = '100%';
    };
  }

  // 预览图片
  onChangeSelectFile(event) {
    const file = event.currentTarget.files[0];
    this.coverImage = file;
    // 必须 bypassSecurityTrustUrl 转换一下 url ，要不能angular会报，说url不安全错误。
    this.coverImageUrl = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(file));
  }

  // 移除封面
  removeCoverImage() {
    this.coverImage = undefined;
    this.coverImageUrl = undefined;
  }

  // 存草稿
  save() {
    if (this.coverImage && this.publishTitle && this.editor['value']) {
      this.saveStatus = 1;
      this.httpPost('draft');
    } else {
      alert('完善封面图、标题、文本后才能保存。');
    }
  }

  // 发布话题
  submit() {
    if (this.coverImage && this.publishTitle && this.editor['value']) {
      this.publishFlag = '发布中...';
      this.httpPost('publish');
    } else {
      alert('完善封面图、标题、文本后才能发布。');
    }
  }

  // using jQuery
  getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = _.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  // 发送请求
  httpPost(status) {
    const _that = this;
    const formData = new FormData();
    formData.append('cover', this.coverImage);
    formData.append('title', this.publishTitle);
    formData.append('content', this.editor['value']);
    formData.append('status', status);
    const xhr = new XMLHttpRequest();
    xhr.addEventListener('load', function (evt) {
      if (xhr.readyState == 4 && xhr.status == 201) {
        if (status == 'draft') {
          _that.date = new Date();
          _that.saveStatus = 2;
        } else if (status == 'publish') {
          _that.publishFlag = '发布';
        }
      } else {
        if (status == 'draft') {
          _that.saveStatus = null;
          alert('保存失败');
        } else if (status == 'publish') {
          alert('发布失败');
        }
      }
    }, false);
    xhr.open('post', 'http://47.93.57.133/api/v1/topic/', true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + this.token);
    xhr.send(formData);
  }

}

